import { combineReducers, createStore, applyMiddleware } from 'redux'
import appReducer, { initialStateApp } from './app/reducers'
import authReducer, { initialStateAuth } from './auth/reducers'
import oauthReducer, { initialStateOAuth } from './oauth/reducers'
import { composeWithDevTools } from 'redux-devtools-extension';
import {createLogger} from 'redux-logger'
import thunk from 'redux-thunk'
import { StoreType } from './types'

// 使用日志打印方法， collapsed让action折叠，看着舒服。
const loggerMiddleware = createLogger({collapsed: true});

// 初始化数据
const initialState: StoreType = {
  app: initialStateApp,
  auth: initialStateAuth,
  oauth: initialStateOAuth
}

// 这里暴露出的是创建store的工厂方法
// 每次渲染都需要重新创建一个store实例
// 防止服务端一直复用旧实例 无法和客户端状态同步
export default function initializeStore(state?: StoreType) {
  const rootReducer = combineReducers({
    app: appReducer(Object.assign({}, initialState.app, state ? state.app : {})),
    auth: authReducer(Object.assign({}, initialState.auth, state ? state.auth : {})),
    oauth: oauthReducer(Object.assign({}, initialState.oauth, state ? state.oauth : {})),
  })
  const store = createStore(
    rootReducer,
    composeWithDevTools(
      applyMiddleware(thunk, loggerMiddleware)
    )
  )
  return store
}

